﻿using System;
using System.IO;
using System.Threading.Tasks;
using TruckScale.Helpers;
using static TruckScale.Helpers.LogHelper;

namespace TruckScale.ViewModels
{
  public partial class MainViewModel
  {
    private CHCNetSDK.NET_DVR_DEVICEINFO_V40 DeviceInfo;
    private CHCNetSDK.NET_DVR_USER_LOGIN_INFO LoginInfo;
    private bool m_bInitSDK = false;
    private void InitMonitorProps()
    {
      try
      {
        if (Global._userID1 != -1)
        {
          CHCNetSDK.NET_DVR_StopRealPlay(Global._userID1);
          CHCNetSDK.NET_DVR_Logout(Global._userID1);
          Global._userID1 = -1;
        }
        if (Global._userID2 != -1)
        {
          CHCNetSDK.NET_DVR_StopRealPlay(Global._userID2);
          CHCNetSDK.NET_DVR_Logout(Global._userID2);
          Global._userID2 = -1;
        }
        if (Global._userID3 != -1)
        {
          CHCNetSDK.NET_DVR_StopRealPlay(Global._userID3);
          CHCNetSDK.NET_DVR_Logout(Global._userID3);
          Global._userID3 = -1;
        }
        if (Global._userID4 != -1)
        {
          CHCNetSDK.NET_DVR_StopRealPlay(Global._userID4);
          CHCNetSDK.NET_DVR_Logout(Global._userID4);
          Global._userID4 = -1;
        }
        CHCNetSDK.NET_DVR_Cleanup();

        m_bInitSDK = CHCNetSDK.NET_DVR_Init();
        if (!m_bInitSDK)
        {
          SetLog($"摄像头初始化失败：{CHCNetSDK.NET_DVR_GetLastError()}", LogType.HardwareLogger, LogLevel.Error);
          return;
        }
      }
      catch (Exception e)
      {
        SetLog($"摄像头初始化失败：{e.Message}", LogType.HardwareLogger, LogLevel.Error);
        return;
      }

      Task.Run(() =>
      {
        if (Convert.ToBoolean(Global._hardwareConfig["Monitor1Enable"]))
        {
          MonitorLogin(ref Global._userID1, Global._hardwareConfig["Monitor1IP"]);
          MonitorPreview(Global._userID1, Global._wnd1Handle);
        }
        if (Convert.ToBoolean(Global._hardwareConfig["Monitor2Enable"]))
        {
          MonitorLogin(ref Global._userID2, Global._hardwareConfig["Monitor2IP"]);
          MonitorPreview(Global._userID2, Global._wnd2Handle);
        }
        if (Convert.ToBoolean(Global._hardwareConfig["Monitor3Enable"]))
        {
          MonitorLogin(ref Global._userID3, Global._hardwareConfig["Monitor3IP"]);
          MonitorPreview(Global._userID3, Global._wnd3Handle);
        }
        if (Convert.ToBoolean(Global._hardwareConfig["Monitor4Enable"]))
        {
          MonitorLogin(ref Global._userID4, Global._hardwareConfig["Monitor4IP"]);
          MonitorPreview(Global._userID4, Global._wnd4Handle);
        }
      });

    }

    private void MonitorLogin(ref int userID, string ip)
    {
      if (userID < 0)
      {
        //设备IP地址或者域名
        byte[] byIP = System.Text.Encoding.Default.GetBytes(ip);
        LoginInfo.sDeviceAddress = new byte[129];
        byIP.CopyTo(LoginInfo.sDeviceAddress, 0);

        //设备用户名
        byte[] byUserName = System.Text.Encoding.Default.GetBytes(Global._hardwareConfig["MonitorUser"]);
        LoginInfo.sUserName = new byte[64];
        byUserName.CopyTo(LoginInfo.sUserName, 0);

        //设备密码
        byte[] byPassword = System.Text.Encoding.Default.GetBytes(Global._hardwareConfig["MonitorPwd"]);
        LoginInfo.sPassword = new byte[64];
        byPassword.CopyTo(LoginInfo.sPassword, 0);

        LoginInfo.wPort = ushort.Parse("8000");//设备服务端口号

        DeviceInfo = new CHCNetSDK.NET_DVR_DEVICEINFO_V40();

        userID = CHCNetSDK.NET_DVR_Login_V40(ref LoginInfo, ref DeviceInfo);

        if (userID < 0)
        {
          SetLog($"{ip}摄像头登录失败：{CHCNetSDK.NET_DVR_GetLastError()}", LogType.HardwareLogger, LogLevel.Error);
        }
        else
        {
          SetLog($"{ip}摄像头登录成功", LogType.HardwareLogger);
        }
      }
    }

    private void MonitorPreview(int userID, IntPtr handle)
    {
      if (userID > -1)
      {
        CHCNetSDK.NET_DVR_PREVIEWINFO lpPreviewInfo = new CHCNetSDK.NET_DVR_PREVIEWINFO
        {
          hPlayWnd = handle,//预览窗口
          lChannel = 1,//预te览的设备通道
          dwStreamType = 1,//码流类型：0-主码流，1-子码流，2-码流3，3-码流4，以此类推
          dwLinkMode = 0,//连接方式：0- TCP方式，1- UDP方式，2- 多播方式，3- RTP方式，4-RTP/RTSP，5-RSTP/HTTP 
          bBlocked = true, //0- 非阻塞取流，1- 阻塞取流
          dwDisplayBufNum = 1, //播放库播放缓冲区最大缓冲帧数
          byProtoType = 0,
          byPreviewMode = 0
        };

        IntPtr pUser = new IntPtr();//用户数据

        int ret = CHCNetSDK.NET_DVR_RealPlay_V40(userID, ref lpPreviewInfo, null/*RealData*/, pUser);

        if (ret < 0)
        {
          SetLog($"{userID}预览画面失败：{CHCNetSDK.NET_DVR_GetLastError()}", LogType.HardwareLogger, LogLevel.Error);
        }
        //else
        //{
        //  SetLog($"{userID}预览画面成功", LogType.HardwareLogger);
        //}
      }
    }

    private void Snap(string weighBtn, string bh)
    {
      switch (weighBtn)
      {
        case "FirstWeighing":
          TakeSnapshots(bh, "_W1_M");
          break;
        case "SecondWeighing":
          TakeSnapshots(bh, "_W2_M");
          break;
        case "OnceWeighing":
          TakeSnapshots(bh, "_W_M");
          break;
        default:
          break;
      }
    }

    private void TakeSnapshots(string bh, string fileNamePrefix)
    {
      string timeStamp = DateTime.Now.ToString("yyyyMMddHHmmss");

      for (int i = 1; i <= 4; i++)
      {
        int userID = (int)typeof(Global).GetField("_userID" + i).GetValue(null);
        if (userID != -1)
        {
          string picName = Path.Combine(Environment.CurrentDirectory, "Snap", bh, timeStamp + fileNamePrefix + i + ".bmp");
          CHCNetSDK.NET_DVR_CapturePicture(userID, picName);
        }
      }
    }
  }
}
